package com.glorysoft.lipuxinpda.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.glorysoft.lipuxinpda.R;
import com.glorysoft.lipuxinpda.adapter.AlarmInfoRecyclerViewAdapter;
import com.glorysoft.lipuxinpda.adapter.DaycheckRecyclerViewAdapter;
import com.glorysoft.lipuxinpda.adapter.LotnginfoAdapter;
import com.glorysoft.lipuxinpda.adapter.RealTimeRecyclerViewAdapter;
import com.glorysoft.lipuxinpda.base.BaseActivity;
import com.glorysoft.lipuxinpda.base.Constant;
import com.glorysoft.lipuxinpda.entity.BaseEntity;
import com.glorysoft.lipuxinpda.entity.ChangeSpotCheckInfoEntity;
import com.glorysoft.lipuxinpda.entity.EqpInfoEntity;
import com.glorysoft.lipuxinpda.entity.LotngInfo;
import com.glorysoft.lipuxinpda.entity.MessageInfoEntity;
import com.glorysoft.lipuxinpda.entity.RealTimeMessageReturnEntity;
import com.glorysoft.lipuxinpda.entity.ShowEndProcessReturnEntity;
import com.glorysoft.lipuxinpda.utils.GsonUtils;
import com.glorysoft.lipuxinpda.utils.NetUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BatchWorkEndActivity extends BaseActivity {
    private Context mContext;

    private LinearLayout llMain;

    private TextView tv_lot_id;//批次号
    private TextView tv_eqp_id;//设备号
    private TextView tv_eqp_type;//设备型号
    private TextView tv_lot_qty_chip;//投料数量
    private TextView tv_start_time;//开始时间
    private TextView tv_end_time;//结束时间
    private RecyclerView rv_data;//不良品分类显示区
    private FreeUI_ClearEditText et_remark;//备注
    private FreeUI_ClearEditText et_qualify_num_star;//合格数(颗)
    private FreeUI_ClearEditText et_scrap_num_star;//报废数(颗)
    private FreeUI_ClearEditText et_actual_output;//实际产量(颗)

    private RecyclerView rv_alarm_data;//报警数据
    private RecyclerView rv_realtime_message;//实时消息

    private String sEqpID;//设备号

    private ShowEndProcessReturnEntity mShowEndProcessReturnEntity;//预结束信息

    private FreeUI_GeneralFragmentDialog mMessageDialog;//消息提示框
    private List<LotngInfo> lotngIngoList;//不良品分类详情
    private LotnginfoAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onStart() {
        super.onStart();

//        String data = "{\n" +
//                "     \"data\":{\n" +
//                "        \"EQPID\":\"2FS101\",\n" +
//                "        \"MessageList\":[\n" +
//                "            {\n" +
//                "                \"CREATED_TIME\":\"2020/10/11 14:11:11\",\n" +
//                "                \"OPERAND\":\"PDA\",\n" +
//                "                \"OPERATION_CONTENT\":\"点击批次开始按钮\",\n" +
//                "                \"MSG_ID\":\"1111\"\n" +
//                "            },\n" +
//                "            {\n" +
//                "                \"CREATED_TIME\":\"2020/10/11 14:21:11\",\n" +
//                "                \"OPERAND\":\"PDA\",\n" +
//                "                \"OPERATION_CONTENT\":\"设备开始作业\",\n" +
//                "                \"MSG_ID\":\"1121\"\n" +
//                "             }]}}";
//        try {
//            JSONObject jsonObject = new JSONObject(data);
//            String sData = jsonObject.getString("data");
//            RealTimeMessageReturnEntity body = GsonUtils.getObject(sData, RealTimeMessageReturnEntity.class);
//            showRealTimeMessage(body);//显示实时消息
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_batch_work_end;
    }

    @Override
    protected void initView() {
        mContext = this;

        llMain = findViewById(R.id.llMain);

        tv_end_time = findViewById(R.id.tv_end_time);
        tv_eqp_id = findViewById(R.id.tv_eqp_id);
        tv_lot_qty_chip = findViewById(R.id.tv_lot_qty_chip);
        tv_lot_id = findViewById(R.id.tv_lot_id);
        tv_start_time = findViewById(R.id.tv_start_time);
        tv_eqp_type = findViewById(R.id.tv_eqp_type);
        rv_data = findViewById(R.id.rv_data);
        et_qualify_num_star = findViewById(R.id.et_qualify_num_star);
        et_remark = findViewById(R.id.et_remark);
        et_scrap_num_star = findViewById(R.id.et_scrap_num_star);
        et_actual_output = findViewById(R.id.et_actual_output);

        rv_alarm_data = findViewById(R.id.rv_alarm_data);
        rv_realtime_message = findViewById(R.id.rv_realtime_message);

    }

    @Override
    protected void initData() {
        Bundle extras = getIntent().getExtras();
        sEqpID = extras.getString("EQPID");

        tv_eqp_id.setText(sEqpID);
        LotngInfo lotngInfo = new LotngInfo();
        for(int i =0;i<10;i++){
            lotngInfo.setNGKEY("测试");
            lotngInfo.setNGVALUE("");
            lotngIngoList.add(lotngInfo);
        }
        //getEndProcess();//预结束
        //getRealTimeMessage();//获取实时消息



        //region 测试
//        String sJson = "{\n" +
//                "   \"data\":{\n" +
//                "    \"LOT_ID\":\"S6L29743-001\",\n" +
//                "\"EQP_TYPE\":\"DAD3350\",\n" +
//                "    \"EQP_ID\":\"2FS103\",\n" +
//                "    \"LOT_QTY_CHIP\":\"87729\",\n" +
//                "    \"START_TIME\":\"2020/8/13 23:01:38\",\n" +
//                "    \"END_TIME\":\"2020/8/14 0:01:06\",\n" +
//                "    \"OUTPUT_QTY_CHIP_EQP\":\"42313\",\n" +
//                "    \"MAINALARM\":[\n" +
//                "    {\n" +
//                "          \"ALARM_MESSAGE\":\"NCS ERROR\",\n" +
//                "          \"ALARM_COUNT\":\"10\"\n" +
//                "         },\n" +
//                "    {\n" +
//                "          \"ALARM_MESSAGE\":\"Hardware ERROR\",\n" +
//                "          \"ALARM_COUNT\":\"12\"\n" +
//                "         }\n" +
//                "      ]\n" +
//                "    }\n" +
//                "}";
//
//        try {
//            String data = new JSONObject(sJson).getString("data");
//            mShowEndProcessReturnEntity = GsonUtils.getObject(data, ShowEndProcessReturnEntity.class);
//            ShowEndProcess();//显示预结束信息
//        }catch (JSONException e){
//            e.printStackTrace();
//        }
        //endregion
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(getString(R.string.batchEndOperation));
        freeUI_titleView.setRightListener(getString(R.string.finishWork), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_actual_output.getText().toString().equals("")){
                    showToast("实际产量不能为空",false);
                    et_actual_output.requestFocus();
                    return;
                }

                if (et_qualify_num_star.getText().toString().equals("")){
                    showToast("合格数不能为空",false);
                    et_qualify_num_star.requestFocus();
                    return;
                }

                if (et_scrap_num_star.getText().toString().equals("")){
                    showToast("报废数不能为空",false);
                    et_scrap_num_star.requestFocus();
                    return;
                }
                endProcess();//结束作业

                //region 测试
//                showMessageDialog(getResources().getString(R.string.end_process_success));

            }
        });
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    //region 接口调用

    //结束作业
    private void endProcess() {
        FreeUI_EntityCallBack<BaseEntity> callBack = new FreeUI_DialogEntityCallBack<BaseEntity>(new TypeToken<BaseEntity>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseEntity> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getSupportFragmentManager())) {
                    finish();
                }
            }

            @Override
            public void onError(Response<BaseEntity> response) {
                super.onError(response);
                loadError(response.getException(), "EndProcess");
            }
        };

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("EQP_ID", sEqpID);//设备号
        map.put("CUR_USERID", Constant.INSTANCE.getLoginEntity().getWORK_NO());//工号
        map.put("LOT_ID", mShowEndProcessReturnEntity.getLOT_ID());//批次号
        map.put("LOT_QTY_CHIP", String.valueOf(mShowEndProcessReturnEntity.getLOT_QTY_CHIP()));//投料产量
        map.put("START_TIME", mShowEndProcessReturnEntity.getSTART_TIME()   );//作业开始时间
        map.put("END_TIME", mShowEndProcessReturnEntity.getEND_TIME());//作业结束时间
        map.put("OUTPUT_QTY", et_actual_output.getText().toString());//实际产量
        map.put("OUTPUT_QTY_OK", et_qualify_num_star.getText().toString());//良品数
        map.put("OUTPUT_QTY_NG", et_scrap_num_star.getText().toString());//报废产量
        String method = Constant.INSTANCE.getNET_URL() + "/EndProcess";
        new NetUtils().requestPostNetNews(method, this, map, callBack);
    }

    //预结束
    private void getEndProcess() {
        FreeUI_EntityCallBack<BaseEntity<ShowEndProcessReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<ShowEndProcessReturnEntity>>(new TypeToken<BaseEntity<ShowEndProcessReturnEntity>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseEntity<ShowEndProcessReturnEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getSupportFragmentManager())) {
                    showToast(response.body().getMessage(), true);

                    mShowEndProcessReturnEntity = response.body().getData().getBody();
                    lotngIngoList = mShowEndProcessReturnEntity.getLotngIngoList();
                    ShowEndProcess();//显示预结束信息
                    showLotnginfoDetail();
                }
            }

            @Override
            public void onError(Response<BaseEntity<ShowEndProcessReturnEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowEndProcess");
            }
        };

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("EQP_ID", sEqpID);//设备号
        map.put("CUR_USERID", Constant.INSTANCE.getLoginEntity().getWORK_NO());//工号
        String method = Constant.INSTANCE.getNET_URL() + "/ShowEndProcessRequest";
        new NetUtils().requestPostNetNews(method, this, map, callBack);
    }

    //获取实时消息
    private void getRealTimeMessage() {
        FreeUI_EntityCallBack<BaseEntity<RealTimeMessageReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseEntity<RealTimeMessageReturnEntity>>(new TypeToken<BaseEntity<RealTimeMessageReturnEntity>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseEntity<RealTimeMessageReturnEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getSupportFragmentManager())) {
                    showToast(response.body().getMessage(), true);

                    RealTimeMessageReturnEntity body = response.body().getData().getBody();
                    showRealTimeMessage(body);//显示实时消息
                }
            }

            @Override
            public void onError(Response<BaseEntity<RealTimeMessageReturnEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "RealTimeMessage");
            }
        };

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("EQP_ID", sEqpID);//设备号
        String method = Constant.INSTANCE.getNET_URL() + "/RealTimeMessage";
        new NetUtils().requestPostNetNews(method, this, map, callBack);
    }

    //endregion

    //显示实时消息
    private void showRealTimeMessage(RealTimeMessageReturnEntity entity) {
        if (entity != null){
            List<MessageInfoEntity> messageList = entity.getMessageList();
            //实时消息适配器
            RealTimeRecyclerViewAdapter mRealTimeRecyclerViewAdapter = new RealTimeRecyclerViewAdapter();

            rv_realtime_message.setLayoutManager(new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL, false));
            rv_realtime_message.setAdapter(mRealTimeRecyclerViewAdapter);
            mRealTimeRecyclerViewAdapter.setmList(messageList);
        }
    }


    //显示预结束信息
    private void ShowEndProcess() {
        if (mShowEndProcessReturnEntity == null){
            return;
        }
        tv_eqp_id.setText(mShowEndProcessReturnEntity.getEQP_ID() == null ? "" : mShowEndProcessReturnEntity.getEQP_ID());
        tv_lot_id.setText(mShowEndProcessReturnEntity.getLOT_ID() == null ? "" : mShowEndProcessReturnEntity.getLOT_ID());
        tv_eqp_type.setText(mShowEndProcessReturnEntity.getEQP_TYPE() == null ? "" : mShowEndProcessReturnEntity.getEQP_TYPE());
        tv_lot_qty_chip.setText(mShowEndProcessReturnEntity.getLOT_QTY_CHIP() == null ? "" : mShowEndProcessReturnEntity.getLOT_QTY_CHIP());
        tv_start_time.setText(mShowEndProcessReturnEntity.getSTART_TIME() == null ? "" : mShowEndProcessReturnEntity.getSTART_TIME());
        tv_end_time.setText(mShowEndProcessReturnEntity.getEND_TIME() == null ? "" : mShowEndProcessReturnEntity.getEND_TIME());

        if (mShowEndProcessReturnEntity.getAlarmInfoEntity().size()>0){
            //报警信息适配器
            AlarmInfoRecyclerViewAdapter mAdapter = new AlarmInfoRecyclerViewAdapter();
            mAdapter.setmList(mShowEndProcessReturnEntity.getAlarmInfoEntity());
            rv_alarm_data.setLayoutManager(new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL, false));
            rv_alarm_data.setAdapter(mAdapter);
        }
    }

    //消息提示框
    private void showMessageDialog(String message) {
        mMessageDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_prompt, null);
        Button btnConfirm = view.findViewById(R.id.btnConfirm);
        TextView tvTips = view.findViewById(R.id.tvTips);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMessageDialog.dismiss();
                finish();
            }
        });
        tvTips.setText(message);
        mMessageDialog.setLayout(view);
//        mDieTypeDialog.getDialog().setCanceledOnTouchOutside(false);
        mMessageDialog.show(getSupportFragmentManager(), "EndProcess");
        mMessageDialog.setCallBack(new FreeUI_CommonCallback() {
            @Override
            public void onSuccess() {
                mMessageDialog = null;
            }
        });

    }
    //展示不良品分类
    private void getChangeSpotCheckInfo() {
        lotngIngoList = new ArrayList<>();
        int childCount = rv_data.getChildCount();
        for (int i = 0; i < childCount; i++) {
            LinearLayout view = (LinearLayout)rv_data.getChildAt(i);
            TextView tv_lotinfoList = view.findViewById(R.id.tv_lotinfoList);
            FreeUI_ClearEditText et_reason = view.findViewById(R.id.et_reason);
            LotngInfo lotngInfo = new LotngInfo();
            lotngInfo.setNGKEY(tv_lotinfoList.getText().toString());
            lotngInfo.setNGVALUE(et_reason.getText().toString());
            lotngIngoList.add(lotngInfo);
        }

        //changeSpotCheckInfo();//提交点检

        //region 测试
//        showDialog("点检成功", true);
        //endregion
    }
    //显示不良品分类项
    private void showLotnginfoDetail() {
        if (lotngIngoList.size() <= 0 ){
            return;
        }
        mAdapter = new LotnginfoAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rv_data.setLayoutManager(linearLayoutManager);
        rv_data.setAdapter(mAdapter);
        mAdapter.setmList(lotngIngoList);
    }

}